﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.IO;
using GameSchool.Models;

namespace GameSchool.Controllers
{
    public class AssignmentController : Controller
    {
        GameSchoolRepository repository = new GameSchoolRepository();
         /*for testing
        private IGameSchoolRepository repository = null;

        public AssignmentController()
        {
            repository = new GameSchoolRepository();
        }

        public AssignmentController(IGameSchoolRepository rep)
        {
            repository = rep;
        }
          */
        

        AssignmentViewModel asign = new AssignmentViewModel();
        //
        // GET: /Assignment/
        #region Views

        public ActionResult ViewAssignmentsInCourse(int CID)
        {
            StudentAssignmentViewModel sViewModel = new StudentAssignmentViewModel();
            sViewModel.itemList = new List<StudentAssignmentViewModel.LevelAndTasksItem>();

            var studentLogin = repository.GetStudentLoginRelationship();
            var theCourse = repository.GetCourseByID(CID);
            sViewModel.sidebarCourses = repository.GetCoursesByStudent(studentLogin).ToList(); //for master view model
            sViewModel.studentName = studentLogin.name; //For master view
            sViewModel.courseName = repository.GetCourseByID(CID).title;
            sViewModel.courseID = CID;
            sViewModel.levels = repository.GetAllLevelsByCourse(theCourse);
            foreach (var item in sViewModel.levels)
            {
                sViewModel.itemList.Add(new StudentAssignmentViewModel.LevelAndTasksItem
                {
                    levelID = item.levelID,
                    levelTitle = item.title,
                    levelNumber = item.number,
                    levelXP = item.intLevelXP,
                    assignmentID = repository.GetAssignmentByLevel(item).assignmentID
                });
            }

            return View(sViewModel);
        }

        //For students, so they can view the assignment description
        [HttpGet]
        public ActionResult ViewAssignment(int? assID, int CID)
        {
            // int id = assID;
            if (!assID.HasValue)
            {
                return View(":( We so sorry, an error occured in GameSchool :( ");
            }
            int id = assID.Value;

            singleAssignmentViewModel vm = new singleAssignmentViewModel();
            var studentLogin = repository.GetStudentLoginRelationship();
            vm.theAssignment = repository.GetAssignmentByID(id);
            vm.sidebarCourses = repository.GetCoursesByStudent(studentLogin).ToList(); //for master view model
            vm.studentName = studentLogin.name; //For master view
            vm.assID = vm.theAssignment.assignmentID;
            vm.studentID = repository.GetStudentLoginRelationship().studentID;
            vm.courseID = CID;

            var theCourse = repository.GetCourses(CID);

            vm.AssignmentList = repository.GetAssignmentByCourseID(CID).ToList();

            return View(vm);
        }
        
        [HttpPost]
        public ActionResult ViewAssignment(int? assID, HttpPostedFileBase file)
        {
            // verify that there was indeed a specific assignment being uploaded
            if (assID.HasValue)
            {
                int id = assID.Value; //convert the id to a non-nullable int
                if (id > 0)
                {
                    Assignment ass = repository.GetAssignmentByID(id);
                    StudentAssignment stuAss = new StudentAssignment();
                    stuAss.assignmentID = id;
                    stuAss.assignment = ass;
                    stuAss.student = repository.GetStudentLoginRelationship();
                    stuAss.studentID = stuAss.student.studentID;
                    
                    

                    // Verify that the user selected a file
                    if (file != null && file.ContentLength > 0)
                    {
                        //convert the file to a byte[] to store in the database
                        using (MemoryStream ms = new MemoryStream())
                        {
                            file.InputStream.CopyTo(ms);
                            byte[] convertedFile = ms.GetBuffer();
                            stuAss.binaryFile = convertedFile;
                        }
                        stuAss.handedInTime = DateTime.Now;
                    }
                    repository.addStudentAssignment(stuAss);
                    repository.Save();
                }
            }
            
            // redirect back to the index action to show the form once again
            return RedirectToAction("ViewAssignment", new { assID });
        }
         
        
        // For students, so they can see all their upcoming and past assignments in a particular course
        public ActionResult ViewAllAssignments(int CID)
        {
            StudentAssignmentsListViewModel viewmodel = new StudentAssignmentsListViewModel();
            viewmodel.upcomingList = new List<StudentAssignmentsListViewModel.upcomingAssignmentItem>();
            var assignmentsInCourse = repository.GetAssignmentByCourseID(CID);

            //TODO: order the list by time limit
            foreach (var item in assignmentsInCourse)
            {
                viewmodel.upcomingList.Add(new StudentAssignmentsListViewModel.upcomingAssignmentItem
                {
                    name = item.title,
                    levelNumber = item.level.number,
                    daysLeft = item.timeLimit,
                    earnedXP = 0, // hardcoded for now because it hasn't been handed in anyway.
                    totalXP = item.assignmentXP
                });
            };

            var studentLogin = repository.GetStudentLoginRelationship();

            viewmodel.studentName = studentLogin.name; //For the top bar
            viewmodel.sidebarCourses = repository.GetCoursesByStudent(studentLogin).ToList();
           // viewmodel.studentID = repository.GetStudentLoginRelationship().studentID;

            viewmodel.courseID = CID;

            var theCourse = repository.GetCourses(CID);
//            viewmodel.levels = repository.GetAllLevelsByCourse(CID);
            return View(viewmodel);
        }

        //For teachers
        public ActionResult CreateAssignment(int CID, int LVID)
        {
            var teacherLogin = repository.GetTeacherLoginRelationship();
            asign.loggedInTeacher = teacherLogin;
            asign.sidebarCourses = repository.GetCoursesByTeacher(teacherLogin).ToList();
            asign.teacherName = teacherLogin.name;
            asign.createAss = repository.GetAssignmentByLevelID(LVID);
            asign.levelID = LVID;
            asign.courseID = CID;
            asign.assignmentID = asign.createAss.assignmentID;
            asign.assignmentXP = asign.createAss.assignmentXP;
            asign.assignmentTitle = asign.createAss.title;
            asign.assignmentDescription = asign.createAss.description;
            asign.assignmentTimeLimit = asign.createAss.timeLimit;
            asign.assignmentFile = asign.createAss.file;


            return View(asign);
        }
        [HttpPost]
        public ActionResult CreateAssignment(FormCollection formData)
        {
            Assignment currentAssignment = new Assignment();

            currentAssignment.levelID = Convert.ToInt32(formData["levelID"]);
            var courseID = Convert.ToInt32(formData["courseID"]);
            var assignmentID = Convert.ToInt32(formData["assignmentID"]);
            currentAssignment.assignmentXP = Convert.ToInt32(formData["assignmentXp"]);
            currentAssignment.title = formData["assignmentTitle"];
            currentAssignment.description = formData["assignmentDescription"];
            currentAssignment.timeLimit = Convert.ToInt32(formData["assignmentTimeLimit"]);
            currentAssignment.file = formData["assignmentFile"];
            currentAssignment.assignmentID = assignmentID;

            repository.UpdateAssignment(currentAssignment);
            repository.Save();
           
            return Redirect("~/Teacher/TeacherHome");
        }

        //For teachers
        public ActionResult AssignmentEdit(int id)
        {
            return View();
        }

        public ActionResult AssignmentEdit(int id, FormCollection formData)
        {
            return View();
        }

        // eiki - teacher gets list of all handed in assignments in a particular course CID
        public ActionResult listAssignments(int CID)
        {
            TeacherXPAssignViewModel vm = new TeacherXPAssignViewModel();
            var teacherLogin = repository.GetTeacherLoginRelationship();

            vm.teacherID = teacherLogin.teacherID;
            vm.teacherName = teacherLogin.name;
            vm.sidebarCourses = repository.GetCoursesByTeacher(teacherLogin).ToList(); //for sidebar.
            vm.teacherName = teacherLogin.name; //for titlebar.
            vm.sidebarCourses = repository.GetCoursesByTeacher(teacherLogin).ToList();
            vm.courseID = CID;
           // vm.courseName = repository.GetTeacherCourse(CID, teacherLogin.teacherID).course.title;
            IQueryable<StudentAssignment> list = repository.getStudentAssignmentsByCourse(CID);
            vm.listStudentAssignments = list.ToList();
            
           // vm.sidebarCourses =; 
            return View(vm);
        }

        /*
        public ActionResult HandInAssignments(IEnumerable<Byte> theFiles, int studentID)
        {
            return View();
        }
         */
        #endregion

        public Notification GetNotifications(Notification theNotification)
        {
            return theNotification;
        }
    }
}
